import { getToken, setToken, getUser, setUser, removeToken } from '@/utils/auth'
import { login, logout } from '@/api/login'

const user = {
    state: {
        token: getToken(),
        user: getUser()
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            setToken(token)
        },
        SET_USER(state, user) {
            state.user = user
            setUser(user)
        }
    },
    actions: {
        Login({ commit }, ruleForm) {
            return new Promise((resolve, reject) => {
                login(ruleForm.username.trim(), ruleForm.password).then(response => {
                    const result = response.data;
                    console.log(response)
                    commit('SET_TOKEN', result.data.token)
                    // commit('SET_USER', result.data.admin)
                    //通知组件已经将token更新成功 resolve成功之后调用
                    resolve(result)
                }).catch(err => {
                    reject(err)
                })
            })
        },

        //退出
        Logout({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(response => {
                    const result = response.data;
                    commit('SET_TOKEN', '')
                    commit('SET_USER', null)
                    removeToken()
                    resolve(result)
                }).catch(err => {
                    reject(err)
                })
            })
        }
    }
}

export default user
